<!--供应商页面-->
<template>
  <!--  新建供应商弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width:1000px;padding:40px;" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="供应商名称">
            <el-input placeholder="请输入供应商" v-model="saveSupplierForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人">
            <el-input placeholder="请输入联系人" v-model="saveSupplierForm.contactPerson"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="电话号码">
            <el-input placeholder="请输入电话号码" v-model="saveSupplierForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱">
            <el-input placeholder="请输入电子邮箱" v-model="saveSupplierForm.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="地址">
            <el-input placeholder="请输入地址" v-model="saveSupplierForm.address" type="textarea"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input placeholder="请输入备注" v-model="saveSupplierForm.notes" type="textarea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveSupplier">确定</el-button>
    </template>
  </el-dialog>
  <!--  搜索供应商 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="供应商名称" style="width:290px">
        <el-input placeholder="请输入供应商名称" style="width:220px;"
                  v-model="searchSupplierForm.name" @keydown.enter="loadSupplier"></el-input>
      </el-form-item>
      <el-form-item label="联系人" style="width:290px">
        <el-input placeholder="请输入联系人" style="width:220px;"
                  v-model="searchSupplierForm.contactPerson" @keydown.enter="loadSupplier"></el-input>
      </el-form-item>
      <el-form-item label="电话号码" style="width:290px">
        <el-input placeholder="请输入电话号码" style="width:220px;"
                  v-model="searchSupplierForm.phone" @keydown.enter="loadSupplier"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadSupplier">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!--  供应商列表展示-->
  <el-card style="margin: 20px;">
    <el-button type="primary" @click="supplierAssets">新增</el-button>
    <el-button type="danger"  @click="batchDelete">批量删除</el-button>
    <el-button type="success" @click="exportSupplier">导出</el-button>
    <el-table style="margin-top: 20px" :data="supplierArr" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="序号" width="80" align="center"/>
      <el-table-column prop="name" label="供应商名称" align="center"/>
      <el-table-column prop="contactPerson" label="联系人" align="center"/>
      <el-table-column prop="phone" label="电话号码" align="center"/>
      <el-table-column prop="email" label="电子邮箱" align="center"/>
      <el-table-column prop="address" label="地址" align="center"/>
      <el-table-column prop="notes" label="备注" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editSupplier(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small" @click="deleteSupplier(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import index from "vuex";
import selectedRows from "core-js/internals/array-iteration";
import * as XLSX from "xlsx";

const dialogTitle = ref('新增供应商');
const dialogVisible = ref(false);
//定义处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭弹窗吗?')){
    saveSupplierForm.value={};
    dialogVisible.value = false;
  }
}

//定义对象用来保存供应商数据
const saveSupplierForm = ref({
  name:'',
  contactPerson:'',
  phone:'',
  email:'',
  address:'',
  notes:''
});

//点击新增按钮时调用
const  supplierAssets= ()=>{
  dialogTitle.value = '新增供应商';
  dialogVisible.value = true;
}
//定义保存虚拟资产的方法
const saveSupplier = ()=>{
  let data = qs.stringify(saveSupplierForm.value);
  axios.post(BASE_URL+'/v1/supplier/save',data).then((response)=>{
    if (response.data.code===2000){
      ElMessage.success("保存成功!");
      saveSupplierForm.value={};
      dialogVisible.value=false;
      loadSupplier();
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//定义对象保存虚拟财产的搜索条件
const searchSupplierForm = ref({
  name:'',
  contactPerson:'',
  phone:''
})

const supplierArr = ref([]);

const loadSupplier = ()=>{
  let data = qs.stringify(searchSupplierForm.value);
  axios.get(BASE_URL+'/v1/supplier/select?'+data).then((response)=>{
    if (response.data.code === 2000){
      supplierArr.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//自动刷新加载供应商数据
onMounted(()=>{
  loadSupplier();
})

//定义重置搜索的方法
const resetSearch = ()=>{
  searchSupplierForm.value = {};
  loadSupplier();
}
//定义编辑资产的方法
const editSupplier = (id) =>{
  dialogVisible.value = true;
  dialogTitle.value = '编辑供应商'
  axios.get(BASE_URL+'/v1/supplier/select?id='+id).then((response)=>{
    if (response.data.code===2000){
      saveSupplierForm.value = response.data.data[0];
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//定义删除资产的方法
const deleteSupplier = (id) =>{
  if (confirm('您确定要删除本供应商吗?')){
    axios.post(BASE_URL+'/v1/supplier/delete/'+id).then((response)=>{
      if (response.data.code === 2000){
        ElMessage.success('删除成功!');
        loadSupplier();
      }else {
        ElMessage.error(response.data.msg);
      }
    })
  }
}



//定义批量删除的数组
const selectedIdsValue = ref([]);
// 监听选择变化
const handleSelectionChange = (selection) => {
  // 更新当前选中的行
  selectedRows.value = selection;
  // 提取所有选中行的ID
  selectedIdsValue.value = selection.map(row => row.id);
};


// 批量删除的方法
const batchDelete = () => {
  if (selectedIdsValue.value.length === 0) {
    Info('请选择要删除的行');
    return;
  }

  let data = selectedIdsValue.value.join(',');
  ElMessageBox.confirm('确定删除选中的供应商吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios.post(BASE_URL + '/v1/supplier/delete/batch/' + data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            loadSupplier();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
};


//定义导出功能
const exportSupplier = async () => {
  loadSupplier(); // 加载用户数据
  try {
    // 定义固定的表头
    const headers = [
      'id', 'name', 'contactPerson', 'phone', 'email', 'address','notes', 'createTime', 'updateTime'
    ];

    // 将 JSON 数据转换为二维数组
    const data = supplierArr.value.map(supplier => headers.map(header => supplier[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空或字段不匹配');
      return;
    }


    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `data_export_${formattedDate}.xlsx`;


    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
};

</script>

<style scoped>

</style>